package com.androidhelper.module.common.http.interceptor;

import android.text.TextUtils;

import com.androidhelper.module.common.utils.LogUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * 日志打印拦截器
 */
public class CustomLoggerInterceptor implements Interceptor
       {

    public static final String TAG = "TAG";
    private String tag;
    private boolean showResponse;

    public CustomLoggerInterceptor(String tag, boolean showResponse) {
        this.tag = tag;
        this.showResponse = showResponse;

    }

    public CustomLoggerInterceptor() {
        this(TAG, true);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //请求日志拦截
        logForRequest(request, chain.connection());
        //执行请求，计算请求时间
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.i("<-- HTTP FAILED: " + e.getMessage());
            throw e;
        }

        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);


        //响应日志拦截
        return logForResponse(response,tookMs);
    }

    private Response logForResponse(Response response, long tookMs) {
        try {

            LogUtils.i("================response'log=================");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            LogUtils.i(clone.request().url() + " (" + tookMs + "ms）"+" response'code:" + clone.code());

            if (!TextUtils.isEmpty(clone.message()))
                LogUtils.i("response'message:" + clone.message());

            if (showResponse) { //showResponse=true 显示返回数据结果
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        LogUtils.i("responseBody's contentType : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            LogUtils.i("responseBody's content : " + resp);

                            body = ResponseBody.create(mediaType, resp);
                            LogUtils.i("=============response'log==============end");
                            return response.newBuilder().body(body).build();
                        } else {
                            LogUtils.i("responseBody's content : maybe [file part] , too large too print , ignored!");
                        }
                    }
                }
            }

            LogUtils.i("=============response'log=============end");
        } catch (Exception e) {
           e.printStackTrace();
        }

        return response;
    }

    private void logForRequest(Request request, Connection connection)  throws IOException {
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;

        try {
            String url = request.url().toString();
            LogUtils.i("==============request'log==============\n"
                    +"requestUrl:" + url+"\n"+"requestType:" + request.method()+"\n"+protocol.toString());

            Headers headers = request.headers();
            if (headers != null && headers.size() > 0) {
                LogUtils.i("requestHeaders:" + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    LogUtils.i("requestBody's contentType:" + mediaType.toString());
                    if (isText(mediaType)) {
                        LogUtils.i("requestBody's content : " + bodyToString(request));
                    } else {
                        LogUtils.i("requestBody's content : maybe [file part] , too large too print , ignored!");
                    }
                }
            }
            LogUtils.i("======================request'log================end");
        } catch (Exception e) {
           e.printStackTrace();
            LogUtils.i(e.getMessage().toString());
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")||
                    mediaType.subtype().equals("x-www-form-urlencoded")
                    )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }
}
